import { orderList, getOrderReturnAddress, orderReturnAddExpress, orderApplyReturn, getReturnExpressList, orderReturnCancel, orderPreAuth, getRenewalGoodsStatus } from "../../api/order";
import { getBtnsByStatus, cancelOrder, cancelRefundApply, payFirstRent, confirmReceipt } from "../../utils/order";
import { programTitle } from "../../setting";
Page({
  data: {
    defaultName: programTitle,
    // tabs: [
    //   { id: 0, title: '全部' },
    //   { id: 2, title: '待付款' },
    //   { id: 101, title: '待审核' },
    //    { id: 108, title: '待支付押金' },
    //   { id: 10, title: '待发货' },
    //   { id: 20, title: '待收货' },
    //   { id: 30, title: '租赁中' },
    //   { id: 40, title: '归还订单' },
    //   { id: 50, title: '续租订单' },
    //   { id: 62, title: '买断订单' },
    //   { id: 60, title: '已完成' },
    //   { id: 1, title: '订单关闭' }
    // ],
       tabs: [
      { id: 0, title: '全部' },
      { id: 2, title: '待付款' },
      { id: 10, title: '待发货' },
      { id: 20, title: '待收货' },
      { id: 30, title: '租赁中' },
      { id: 40, title: '归还订单' },
      { id: 50, title: '续租订单' },
      { id: 62, title: '买断订单' },
      { id: 11, title: '申请退款' },
      { id: 60, title: '已完成' },
      { id: 1, title: '订单关闭' }
    ],
    activeTab: 0,
    orderList: [],
    page: 1,
    pageSize: 10,
    total: 0,
    loadTip: '',
    showLoading: false,
    showTopBtn: false,
    isloading: true,
    showService: false,
    currentMId: '',
    returnAddress: {},
    addressModal: false,
    addressBtn: [
      { text: '取消', extClass: 'button1' },
      { text: '复制地址', extClass: 'button2' },
    ],
    addressOneBtn: [
      { text: '返回', extClass: 'button1' },
    ],
    returnModal: false,
    returnBtn: [
      { text: '取消', extClass: 'button1' },
      { text: '确认归还', extClass: 'button2' },
    ],
    returnApplyBtn: [
      { text: '取消申请', extClass: 'button1' },
      { text: '确认申请', extClass: 'button2' },
    ],
    order_id: '',
    status: 0,
    flowModal: false,
    flowList: [],
    flowIndex: -1,
    flowNo: '',
    placeholder: '请填写物流单号',
    disabledInput: false,
    reletModal: false,
    goodsStatus: '',
    goodsId: '',
    setmealId: ''
  },
  onLoad(options) {
    if(options.order_status){
      const index = this.data.tabs.findIndex(item => item.id == options.order_status);
      this.setData({
        activeTab: index || 0
      })
    }else{
      this.setData({
        activeTab:  0
      })
    }
  },
  onShow(){
    this.getList();
    this.setData({
      reletModal: false,
    })
  },
  getList(flag) {
    // flag为true时加载更多
    const { tabs, activeTab, page, pageSize } = this.data;
    const order_status = tabs[activeTab].id || null;
    const params = order_status ? {
      order_status, page: flag ? page + 1 : 1,
      pageSize
    } : {
        page: flag ? page + 1 : 1,
        pageSize
      };
    this.setData({
      isloading: true
    })

    orderList(params).then(res => {
      my.stopPullDownRefresh();
      for (let item of res.data) {
        item.btns = getBtnsByStatus(item);
        item.showMore = false;
      }
      let list = [...this.data.orderList];
      if (flag) {
        list = [...list, ...res.data];
      } else {
        list = res.data;
      }
      this.setData({
        orderList: list,
        page: res.current_page,
        total: res.total,
        isloading: false,
        showLoading: false
      })
    }).catch(err => {
      my.stopPullDownRefresh();
    })
  },
  goToShop(e) {
    const member_id = e.currentTarget.dataset.id;
    const shopname = e.currentTarget.dataset.shopname;
    my.navigateTo({
      url: '../storeDetails/storeDetails?member_id=' + member_id  +"&shopname=" +shopname
    });
  },
  goToHome() {
    my.switchTab({
      url: '../index/index'
    });
  },
  goToDetail(e) {
    const order_id = e.currentTarget.dataset.id;
    my.navigateTo({
      url: '../user/orderpay/orderpay?id=' + order_id
    });
  },
  handleTabClick({ index, tabsName }) {
    this.setData({
      [tabsName]: index
    });
    my.pageScrollTo({
      scrollTop: 0
    });
    this.getList();
  },
  btnClick(e) {
    const that = this;

    const { index, id, status, order_id, isAuth, pay_type, esignUserId, flowId, sign_status, member_id, goods_id, contract_type } = e.currentTarget.dataset;

    this.setData({
      order_id,
      status
    })
    if (index || index === 0) {
      const { orderList } = this.data;
      orderList[index].showMore = false;
      this.setData({ orderList });
    }
    if (id == 2) {
      cancelOrder(order_id, function () {
        that.getList();
      })
    }
    if (id == 9) {
      my.navigateTo({
        url: '../applyRefund/applyRefund?order_id=' + order_id
      });
    }
    if (id == 18) {
      cancelRefundApply(order_id, function () {
        that.getList();
      })
    }
    if (id == 3 && status == 20) {
      confirmReceipt(order_id, function () {
        that.getList();
      })
    }
    if ((id == 6 && status == 44) || id == 19) {
      my.navigateTo({
        url: '../logistics/logistics?order_id=' + order_id + '&status=' + status
      });
    }
    if (id == 4) {
      my.navigateTo({
        url: '../bill/bill?order_id=' + order_id
      });
    }
    if ((id == 1 || id == 20) && (status == 2 || sign_status != 2)) {
      my.navigateTo({
        url: '../authentication/authentication?orderId=' + order_id + '&payType=' + pay_type + '&isAuth=' + isAuth + '&esignUserId=' + esignUserId + '&flowId=' + flowId + '&status=' + status + '&contractType=' + contract_type
      });
    }
    if ((id == 1 || id == 20) && (status == 3 && sign_status == 2)) {
      // payFirstRent(order_id, function () {
      //   that.getList();
      // })
      my.navigateTo({
        url: '../bill/bill?order_id=' + order_id
      })
    }
    if (id == 17) {
      this.setData({
        currentMId: member_id,
        showService: true
      })
    }
    if (id == 7) {
      my.navigateTo({
        url: '../productDetails/productDetails?goodsId=' + goods_id
      });
    }
    if (id == 14) {
      my.navigateTo({
        url: '../buyout/buyout?orderId=' + order_id
      });
    }
    // 立即归还
    if (id == 11) {
      if(status == 40){
        this.setData({
          returnModal: true
        })
      } else if(status == 42){
        getReturnExpressList().then(res =>{
          that.setData({
            returnModal: false,
            flowModal: true,
            flowList: res
          });
        })
      }
    }
    // 获取归还地址
    if (id == 16) {
      getOrderReturnAddress(order_id).then(res => {
        if(res){
          this.setData({
            returnAddress: res,
            addressModal: true
          })
        }
      }).catch(err => {
        this.setData({
          addressModal: false
        })
      })
    }
    // 取消归还
    if(id == 5){
      orderReturnCancel(order_id).then(res =>{
        my.showToast({
          type: 'none',
          content: '操作成功',
          duration: 1000,
        });
        that.getList();
      })
    }
    // 申请归还
    if(id == 10){
      this.setData({
        returnModal: true
      })
    }
    // 再次申请
    if(id == 12){
      orderApplyReturn(order_id).then(res =>{
        that.getList();
      })
    }
    // 重新签约
    if(id == 22){
      that.againPreAuth()
    }
    // 申请续租
    if(id == 15){
      getRenewalGoodsStatus(order_id).then(res =>{
        console.log('res',res)
        const {goods_id, setmeal_id, status } = res
        if(status == 1){
          this.setData({
            reletModal: true,
            goodsStatus: status,
            goodsId: goods_id,
            setmealId: setmeal_id
          })
        } else {
          this.setData({
            reletModal: true,
            goodsStatus: '',
          })
        }
      }).catch(err =>{
        this.setData({
          reletModal: false,
          goodsStatus: '',
        })
      })
    }
  },
  onReletClick(){
    const {goodsId, setmealId, goodsStatus, order_id } = this.data
    if(!goodsStatus){
      this.setData({
        reletModal: false,
        goodsStatus: ''
      })
    } else {
      my.navigateTo({
        url: "../productDetails/productDetails?goodsId=" +goodsId+ '&setmealId=' +setmealId+ '&is_renewal=' +1+ '&parent_order_id=' + order_id
      })
    }
  },
  // 签约预授权
  againPreAuth(){
    const that = this
    console.log('qianyue',that.data.order_id)
    orderPreAuth(that.data.order_id).then(res =>{
        if(res.orderStr){
          my.tradePay({
            orderStr: res.orderStr,
            success: (res) => {
              that.getList();
              // if(res.resultCode == 9000){}
            },
            fail: (res) => {
              my.showToast({
                type: 'fail',
                content: '签约失败，请稍后重试',
                duration: 1000,
              });
            }
          });
        }
    })
  },
  onAddressClick(e) {
    let index = e.target.dataset.index
    if (index == 0) {
      this.setData({
        addressModal: false,
      });
    } else {
      my.setClipboard({
        text: this.data.returnAddress,
        success: () => {
          my.showToast({
            type: 'none',
            content: '复制成功',
            duration: 1000,
          });
        }
      });
    }
  },
  onReturnClick(e) {
    const that = this
    let index = e.target.dataset.index
    console.log('index',index)
    if (index == 0) {
      that.setData({
        returnModal: false,
      });
    } else {
      const {order_id, status} = that.data
      if(status == 40){
        getReturnExpressList().then(res =>{
          that.setData({
            returnModal: false,
            flowModal: true,
            flowList: res
          });
        })
      } else if( status==30|| status==39 ){
        // console.log('未到期',status, order_id)
        orderApplyReturn(order_id).then(res =>{
          that.getList();
          that.setData({
            returnModal: false
          });
        })
      }
    }
  },
  bindPickerChange(e){
    this.setData({
      flowIndex: e.detail.value,
      disabledInput: e.detail.value == 0 ? true : false,
      placeholder: e.detail.value == 0 ? '无需填写单号' : '请填写物流单号',
    });
  },
  onFlowNo(e){
    let reg = /^[0-9A-Za-z]+$/
    console.log(reg.test(e.detail.value))
    if(!reg.test(e.detail.value)){
      my.showToast({
        type: 'none',
        content: '请填写正确的物流单号',
        duration: 1500,
      });
    }
    this.setData({ flowNo: e.detail.value })
  },
  toAddFlow(){
    const that = this
    const { order_id, flowIndex, flowNo, flowList} = that.data
    const reg = /^[0-9A-Za-z]+$/
    if(flowIndex < 0){
      my.showToast({
        type: 'none',
        content: '请选择物流名称',
        duration: 1500,
      });
      return false 
    }
    if(!flowNo && flowIndex >0){
      my.showToast({
        type: 'none',
        content: '请填写物流单号',
        duration: 1500,
      });
      return false 
    }
    if(flowNo && !reg.test(flowNo)){
      my.showToast({
        type: 'none',
        content: '请填写正确的物流单号',
        duration: 1500,
      });
      return false
    }
    orderReturnAddExpress({
      order_id,
      logistics_name: flowList[flowIndex].name,
      logistics_no: flowNo,
    }).then(res =>{
      this.setData({
        flowModal: false
      });
      that.getList();
    })
  },
  closeModal(){
    this.setData({
      flowModal: false
    })
  },
  closeService() {
    this.setData({
      showService: false
    })
  },
  clickMore(e) {
    const index = e.currentTarget.dataset.index;
    const list = [...this.data.orderList];
    list[index].showMore = !list[index].showMore;
    this.setData({
      orderList: list
    })
  },
  onReachBottom() {
    // 页面拉到底部
    const { orderList, total } = this.data;
    if (orderList.length < total) {
      this.setData({
        showLoading: true
      })
      this.getList(true);
    } else if (total > 4) {
      this.setData({
        loadTip: '没有更多数据了'
      })
    }
  },
  onPullDownRefresh() {
    this.getList();
  },
  onPageScroll(e) {
    this.setData({
      showTopBtn: e.scrollTop > 600
    })
  }
});
